package com.lmbx.shzh.exception;

import com.lmbx.shzh.domain.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;

/**
 * @Auther: wyl
 * @Date: 2021/5/11
 * @Description:
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    private static final String errInfo = "接口服务出错啦!";

    /**
     * 校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult exceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + ";";
        }
        log.error("捕捉到参数异常：", e);
        return ResponseResult.error(ErrorCodeEnum.PARAM_ERROR.getCode(), errorMesssage);
    }


    /**
     * ValidationException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ValidationException.class)
    @ResponseBody
    public ResponseResult handleValidationException(ValidationException e) {
        log.error("捕捉到参数校验异常", e);
        return ResponseResult.error(ErrorCodeEnum.PARAM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 拦截业务类异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult businessExceptionHandle(BusinessException e) {
        log.error("捕捉到业务类异常：", e);

        return ResponseResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 拦截运行时异常
     *
     * @param e
     */
    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseResult runtimeExceptionHandle(RuntimeException e) {
        log.error("捕捉到运行时异常：", e);

        return ResponseResult.error(ErrorCodeEnum.UNKNOWN_ERROR.getCode(), e.getMessage());
    }

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult errorHandler(Exception ex) {
        log.error(errInfo, ex);
        return ResponseResult.error(-1, ex.getMessage());
    }

    /**
     * 捕捉系统级异常
     *
     * @param th
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Throwable.class)
    public ResponseResult throwableHandle(Throwable th) {
        log.error("捕捉Throwable异常：", th);

        return ResponseResult.error(ErrorCodeEnum.SYSTEM_ERROR.getCode(), th.getMessage());
    }
}
